<template>
  <el-dialog :title="title" :visible.sync="visible" width="350px" append-to-body :close-on-click-modal="false">
    <el-form ref="form" :model="form" :rules="rules" label-width="120px">
      <el-row>
        <el-col :span="24">
          <el-input v-model="form.groupName" placeholder="一个合理的分组名称可以方便团队协作" maxlength="20" show-word-limit/>
        </el-col>
      </el-row>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="cancel">取 消</el-button>
    </div>
  </el-dialog>
</template>
<script>
  import {updateGroup, addGroup} from "@/api/hawkeye/group";

  export default {
    name: "GroupModalForm",
    props: {},
    data() {
      return {
        title: "",
        visible: false,
        form: {},
        rules: {
          groupName: [
            {required: true, message: "", trigger: "blur"}
          ]
        }
      };
    },
    methods: {
      open(data) {
        this.reset();
        if (data != undefined && data.id != undefined) {
          this.$set(this.form, "id", data.id)
          this.$set(this.form, "groupName", data.name)
          this.title = "编辑分组"
        } else {
          this.title = "新增分组"
        }
        this.visible = true;
      },
      submitForm() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.id != undefined) {
              updateGroup(this.form).then(res => {
                this.$modal.msgSuccess("修改成功");
                this.visible = false;
                this.$emit("submitted", res);
              });
            } else {
              addGroup(this.form).then(res => {
                this.$modal.msgSuccess("新增成功");
                this.visible = false;
                this.$emit("submitted", res);
              });
            }
          }
        });
        this.reset();
      },
      cancel() {
        this.visible = false;
        this.reset();
        this.$emit("cancel");
      },
      reset() {
        this.form = {};
        this.resetForm("form");
      },
    }
  }
</script>
